package com.ms.p2p.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.bean.Message;
import com.ms.common.exception.NoticeException;
import com.ms.common.utils.*;

import com.ms.p2p.Constants;
import com.ms.p2p.controller.BaseController;
import com.ms.p2p.entity.member.Auth;
import com.ms.p2p.entity.member.Email;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.provider.*;
import com.ms.p2p.plugin.validation.annotation.RequiredStringValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;

/**
 * 认证审核
 */
@Controller
@RequestMapping({ "/member/auth" })
public class AuthController extends BaseController {
	@Reference
	private AdminUserProvider adminUserProvider;
	@Reference
	private CertiFiCationProvider certificationProvider;

	@Reference
	private SendProvider sendProvider;

	@Reference
	private MailAuthProvider mailAuthProvider;

	@Reference
	private MemberProvider memberProvider;

	@Reference
	private IdCardQueryProvider idCardQueryProvider;

	@Reference
	private SettingProvider settingProvider;

	@Reference
	private SendProvider smsService;

	@RequestMapping({ "/vip" })
	public String kefu(HttpServletRequest request, HttpSession session) {
		Member principal = getCurrentUser();
		Integer kefu_id = memberProvider.findById(principal.getId()).getKefu_id();
		request.setAttribute("kefu_id", kefu_id);
		request.setAttribute("iskefu", kefu_id == null ? "0" : "1");
		request.setAttribute("kefus", adminUserProvider.findByDepart(31));
		return "/customer/member/ucenter/kefu/input";

	}

	/**
	 * 申请实名认证
	 */
	@RequestMapping("/certification")
	@ResponseBody
	public Message certification(HttpServletRequest request, HttpSession session

			, @RequestParam("real_name") String real_name
			, @RequestParam("idnumber") String idnumber

	) {
		Auth	realName = new Auth();
		Member user = getCurrentUser();
		try {
		int other = certificationProvider.findOther(idnumber, user.getId());
		if(other>0){
			throw  new NoticeException("同一张身份证在本平台不能注册2次");
		}



			realName.setUser_id(user.getId());
		realName.setReal_name(real_name);
		realName.setId_number(idnumber);
		realName.setAddtime(MsDateUtils.getTime());
		realName.setAddip(AppContext.getRemoteIp());
		realName.setStatus(0);
		String birthday;

		int sex = 0;

		if(idnumber.length()==15){
			birthday=idnumber.substring(6,12);


		}else if(idnumber.length()==18){
			birthday=idnumber.substring(6,14);
		}else{
			throw  new NoticeException("身份证有误");
		}

		if (idnumber.length() == 15 || idnumber.length() == 18)
		{
			String lastValue = idnumber.substring(idnumber.length() - 1, idnumber.length());

			if (lastValue.trim().toLowerCase().equals("x")||lastValue.trim().toLowerCase().equals("e"))
			{
				sex = 0;
			}
			else
			{
				sex = Integer.parseInt(lastValue) % 2;

			}
		}
		realName.setSex(sex);
		realName.setBirthdate(birthday);//生日奖励发放



		if(idCardQueryProvider.idCardQuery(idnumber,real_name)){



				realName.setStatus(1);

                certificationProvider.insert(realName);
        }else{
			realName.setStatus(0);

		}
		} catch (NoticeException e) {
			realName.setStatus(0);
		}
		catch (Exception e) {
			logger.error(e);
			return Message.success("出现未知错误");
		}
		if(certificationProvider.findByUserId(user.getId())!=null){
			realName.setId(certificationProvider.findByUserId(user.getId()).getId());
			certificationProvider.update(realName);
		}else{
			certificationProvider.insert(realName);
		}



		if(realName.getStatus()==1)
		return Message.success("认证成功");
		return Message.error("身份证错误");

	}


	/**
	 *  认证邮箱 、手机
	 */
	@RequestMapping({"/{type}"})
	public String toApprove(@PathVariable String type, Model model) {

		model.addAttribute("type", type);
		Member user = getCurrentUser();

		//邮箱
		if ("email".equals(type)) {
			Email e = mailAuthProvider.findByUserId(user.getId());
			model.addAttribute("emailApr", e);
			return "customer/member/ucenter/auth/email";
		}

		//手机
		Member member = memberProvider.findById(user.getId());
		model.addAttribute("mobile", member.getMember_phone());

		return "customer/member/ucenter/auth/mobile";
	}


	/**
	 * 手机换绑时获取验证码
	 */
	@RequestMapping("/SendSmsAuth")
	@ResponseBody
	public String ajaxSendSmsForModifyMobile(String mobile, Boolean newMobile, HttpServletResponse response) throws IOException, TemplateException {

		if(newMobile){ //原手机号验证
			//发送校验
			String msg = isValidSms(mobile, null, false);
			if(StringUtils.isNotBlank(msg)){
				return ResponseUtils.renderJSON(Message.error(msg), response);
			}

			if(StringUtils.isBlank(mobile) ||  memberProvider.findByMobilePhone(mobile) != null){
				return ResponseUtils.renderJSON(Message.error("新的手机号码已存在，不能被绑定！"), response);
			}
		}else{
			Member user = memberProvider.findById(getCurrentUser().getId());
			mobile = user.getMember_phone();
			String msg = isValidSms(mobile, null, false);
			if(StringUtils.isNotBlank(msg)){
				return ResponseUtils.renderJSON(Message.error(msg), response);
			}
		}
		FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");
		//
		String mobileCode = CommonUtil.getRandomNum(6);
		String nickname = settingProvider.findByCode("email_from_name")
				.getText();
		String templatePath = Constants.TEMPLATE_SMS_BIND;
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		Template template = configuration.getTemplate(templatePath, "utf-8");
		HashMap map = new HashMap();
		map.put("code",mobileCode);
		String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
		// 发送短信
		Message message = smsService.sendSMS(mobile,"【"+nickname+"】"+content, "手机换绑", 0);

		if (newMobile) {
			AppContext.setSessionAttr(Constants.AUTH_NEW_MOBILE_CODE_SESSION_KEY, mobileCode + "_" + System.currentTimeMillis());
		}else if(!newMobile ){
			AppContext.setSessionAttr(Constants.AUTH_OLD_MOBILE_CODE_SESSION_KEY, mobileCode + "_" + System.currentTimeMillis());
		}
		return ResponseUtils.renderJSON(message, response);
	}


	@RequestMapping({"/mobileauth"})
	@ResponseBody
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "code1", message = "老手机验证码不能为空"),
			@RequiredStringValidator(fieldName = "newmobile", message = "新手机号码不能为空"),
			@RequiredStringValidator(fieldName = "code2", message = "新手机验证码不能为空")})
	public Message mobileauth(HttpServletRequest request,
							  HttpSession session,
							  @RequestParam("code1") String code1,
							  @RequestParam("newmobile") String newmobile,
							  @RequestParam("code2") String code2)
			throws IllegalAccessException, InvocationTargetException,
			IntrospectionException {



		String code1validate = (String) AppContext.getSessionAttr(Constants.AUTH_OLD_MOBILE_CODE_SESSION_KEY);

		//原手机验证码验证
		String[] codes = StringUtils.split(code1validate, "_");
		if(codes == null || codes.length != 2
				|| System.currentTimeMillis() - Long.valueOf(codes[1]) > 1000*60*10
				|| StringUtils.isBlank(codes[0]) || !StringUtils.equals(codes[0], code1) ){

			throw new NoticeException("原手机验证码错误或过期无效");
		}
		//新手机验证码验证
		String code2validate = (String) AppContext.getSessionAttr(Constants.AUTH_NEW_MOBILE_CODE_SESSION_KEY);
		String[] codes2 = StringUtils.split(code2validate, "_");
		if(codes2 == null || codes2.length != 2
				|| System.currentTimeMillis() - Long.valueOf(codes2[1]) > 1000*60*10
				|| StringUtils.isBlank(codes2[0]) || !StringUtils.equals(codes2[0], code2) ){

			throw new NoticeException("新手机验证码错误或过期无效");
		}

		Member user = getCurrentUser();
		Member user2 = memberProvider.findByMobilePhone(newmobile);
		if (user2 != null) {
			throw new NoticeException("新手机号码已被注册");
		}

		memberProvider.updateMobilePhoneById(newmobile, user.getId());

		user.setMember_phone(newmobile);
		session.setAttribute("mobileCode", null);
		return Message.success("手机号码换绑成功！");
	}


	/**
	 * 发送邮件
	 */
	@RequestMapping(value = {"/emailAuth"})
	@ResponseBody
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "email", message = "emial不能为空")})
	public Message emailAuth(HttpServletRequest request, HttpSession session)
			throws IntrospectionException, IllegalAccessException,
			InvocationTargetException, IOException, TemplateException {

		String email = request.getParameter("email");
		Member user = getCurrentUser();
		String rand_code = CommonUtil.getRandomNum(6);
		Email emailObj = mailAuthProvider.findByUserId(user.getId());
		if (memberProvider.findNotUserIdAndEmail(user.getId(), email) > 0) {
			throw new NoticeException("该邮箱已经被认证");
		}
		if (emailObj == null) {
			emailObj = new Email();
			emailObj.setUser_id(user.getId());
			emailObj.setRand_code(rand_code);
			emailObj.setIs_passed("0");
			mailAuthProvider.insert(emailObj);
			user.setEmail(email);
			memberProvider.updateById(user);
		} else {
			emailObj.setRand_code(rand_code);
			emailObj.setIs_passed("0");
			mailAuthProvider.update(emailObj);
			user.setEmail(email);
			memberProvider.updateById(user);
		}
		FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");
		String templatePath = Constants.TEMPLATE_MAIL_BIND;
		String subject = "邮箱认证";
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		Template template = configuration.getTemplate(templatePath, "utf-8");
		String username = user.getUser_name();
		HashMap map = new HashMap();
		map.put("username",username);
		map.put("code",rand_code);
		String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
		sendProvider.sendMail(email,subject,content);
		return Message.success("邮件发送成功！");
	}

	/**
	 * 邮箱人认证
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping({"/ac"})
	@ResponseBody
	public Message activateUser(HttpServletRequest request)
			throws IntrospectionException, IllegalAccessException,
			InvocationTargetException {

		String email = request.getParameter("email");
		String randCode = request.getParameter("randCode");
		Member user = memberProvider.findByEmail(email);
		if (user != null) {
			Email emailObj = mailAuthProvider.findByUserId(user.getId());
			if ((emailObj.getRand_code().equals(randCode)) && (emailObj.getIs_passed().equals("0"))) {
				emailObj.setIs_passed("1");
				mailAuthProvider.update(emailObj);
			}else{
				throw new NoticeException("验证码过期");
			}

		} else {
			throw new NoticeException("用户不存在");
		}
		return Message.success("邮箱认证成功");
	}
}
